#/bin/bash

echo "rtc_rtc2pi" | nc -q 0 127.0.0.1 8423
cd /home/pi/pipaper
[ -e config ] || mkdir config
[ -e config/config.sh ] || cp script/config.sh config/

. script/config.sh
if [ "$forceupdate" = "true" ]; then
    if ping gitee.com -c 1 && git fetch && git pull 
    then 
        sed -i "/updatedate/c updatedate=\"$(date +%Y-%m-%d)\"" config/config.sh
        #chmod 755 script/*.sh
    fi
fi

. config/config.sh
if [ "$updatedate" != "$(date +%Y-%m-%d)" ]; then
    if ping gitee.com -c 1 && git fetch && git pull 
    then 
        sed -i "/updatedate/c updatedate=\"$(date +%Y-%m-%d)\"" config/config.sh
        #chmod 755 script/*.sh
    fi
fi


[ "$activate" = "true" ] || sleep 15
# 判断是否要设置启动
. config/config.sh
if [ "$needtostart" = "true" ]; then
    sed -i "/needrtcalarm/c needrtcalarm=true" config/config.sh
    sed -i "/activate/c activate=true" config/config.sh
    sed -i "/needtostart/c needtostart=false" config/config.sh
fi

# 判断是否要执行刷新
. config/config.sh
if [ "$activate" = "true" ]; then
    echo change picture
    python3 src/printpic.py
    if [ "$needpush" = "true" ] ; then
        echo "execute $(date -Iminutes)  $(echo "get battery" | nc -q 0 127.0.0.1 8423)" >> log/run.log
        ping gitee.com -c 1 && git commit -a -m "$(date +%Y-%m-%d) $(date +%H:%M:%S)" && git push
    fi
fi


# 判断是否要执行清屏
. config/config.sh
if [ "$cleanscreen" = "true" ]; then
    echo cleanscreen
    python3 src/clear.py
    sed -i "/needtostop/c needtostop=true" config/config.sh
    sed -i "/cleanscreen/c cleanscreen=false" config/config.sh
fi

. config/config.sh
if [ "$needtostop" = "true" ]; then
    sed -i "/activate/c activate=false" config/config.sh
    sed -i "/needrtcalarm/c needrtcalarm=false" config/config.sh
    sed -i "/needtostop/c needtostop=false" config/config.sh
fi

. config/config.sh
if [ "$needrtcalarm" = "true" ]; then
    #echo "rtc_alarm_set $(date -Iseconds -d "$internal minutes") 127" | nc -q 0 127.0.0.1 8423
    echo moved to python script 
else 
    echo "rtc_alarm_disable" | nc -q 0 127.0.0.1 8423
fi

. config/config.sh
[ "$activate" = "false" ] && sleep 600
if [ "$needtoshutdown" = "true" ]; then
    shutdown now
    echo shutdown
fi
